package com.cloudwise.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cloudwise.entity.Dept;
import com.cloudwise.entity.ReturnBean;
import com.cloudwise.entity.User;
import com.cloudwise.entity.UserRole;
import com.cloudwise.service.DeptService;
import com.cloudwise.service.UserRoleService;
import com.cloudwise.service.UserService;
import com.cloudwise.util.MD5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;

/**
 * 用户信息表(User)表控制层
 *
 * @author
 * @since 2021-12-03 15:15:36
 */
@RestController
@RequestMapping("user")
public class UserController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;
    @Resource
    private DeptService deptService;
    @Resource
    private UserRoleService userRoleService;

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param user 查询实体
     * @return 所有数据
     */
    @GetMapping
    public ReturnBean selectAll(Integer page, Integer limit, User user) throws IllegalAccessException {
        Page<User> pageObj = new Page<>(page, limit);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(user.getUserName())) {
            queryWrapper.like("user_name", user.getUserName());
        }
        if (ObjectUtil.isNotEmpty(user.getPhone())) {
            queryWrapper.like("phone", user.getPhone());
        }
        Page<User> page1 = this.userService.page(pageObj, queryWrapper);
        List<Dept> list = deptService.list();
        List<Map<String, Object>> userVoList = new ArrayList<>();
        for (User record : page1.getRecords()) {
            for (Dept dept : list) {
                if (record.getDeptId().equals(dept.getDeptId())) {
                    Map<String, Object> userVo = new HashMap<>();
                    userVo.put("deptName", dept.getDeptName());
                    Field[] fields = record.getClass().getDeclaredFields();
                    for (Field field : fields) {
                        field.setAccessible(true);
                        userVo.put(field.getName(), field.get(record));
                    }
                    userVoList.add(userVo);
                }
            }
        }
        return super.success(userVoList, page1.getTotal());

    }

    /**
     * @param user
     * @return java.lang.String
     * @create by: Teacher陈（86521760@qq.com）
     * @description:登录方法
     * @create time: 2021/12/3 15:19
     */
    @PostMapping("login")
    public ReturnBean login(@RequestBody User user) {
        //获取shiro的主体，subject
        Subject subject = SecurityUtils.getSubject();
        //构建用户登录的令牌
        UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginName(), user.getPassword());
        //登录操作
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            //用户不存在
            return super.fail(user, "用户名不存在");
        } catch (IncorrectCredentialsException ie) {
            return super.fail(user, "密码不正确");
        }
        //获取当前登录的用户
        Object principal = subject.getPrincipal();
        return success(principal);
    }

    @RequestMapping("/insert")
    public ReturnBean insert(User user, @RequestParam("roleIds[]") List<Integer> roleIds) {
        user.setCreateTime(new Date());
        user.setSalt(UUID.randomUUID().toString().substring(0, 32));
        user.setPassword(MD5Utils.md5(user.getPassword(), user.getSalt()));
        boolean save;

        QueryWrapper<User> loginNameQueryWrapper = new QueryWrapper<>();
        loginNameQueryWrapper.eq("login_name",user.getLoginName());
        loginNameQueryWrapper.ne("flag",1);
        User loginNameOne = userService.getOne(loginNameQueryWrapper);

        QueryWrapper<User> emailQueryWrapper = new QueryWrapper<>();
        emailQueryWrapper.eq("email",user.getEmail());
        emailQueryWrapper.ne("flag",1);
        User emailOne = userService.getOne(emailQueryWrapper);

        QueryWrapper<User> phoneQueryWrapper = new QueryWrapper<>();
        phoneQueryWrapper.eq("phone",user.getPhone());
        phoneQueryWrapper.ne("flag",1);
        User phoneOne = userService.getOne(phoneQueryWrapper);

        if(!ObjectUtil.isEmpty(loginNameOne)) {
            return fail(null,"用户名已经被使用过了");
        }
        if(!ObjectUtil.isEmpty(emailOne)) {
            return fail(null,"邮箱已经被使用过了");
        }
        if(!ObjectUtil.isEmpty(phoneOne)) {
            return fail(null,"手机号已经被使用过了");
        }

        save = userService.save(user);
        List<UserRole> userRoleList = new ArrayList<>();
        for (Integer roleId : roleIds) {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(roleId);
            userRoleList.add(userRole);
        }
        boolean saveBatch = userRoleService.saveBatch(userRoleList);
        if (save && saveBatch) {
            return super.success(null);
        } else {
            return super.fail(null);
        }
    }

    @DeleteMapping("/delete")
    public ReturnBean delete(@RequestParam("idList[]") List<Integer> idList) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", idList);
        boolean removeUserRole = userRoleService.remove(queryWrapper);
        boolean removeByIds = userService.removeByIds(idList);
        if (removeByIds && removeUserRole) {
            return super.success(null);
        } else {
            return super.fail(null);
        }
    }

    @PutMapping("/update")
    public ReturnBean update(User user, @RequestParam("roleIds[]") List<Integer> roleIds) {
        user.setUpdateTime(new Date());
        boolean updateById = userService.updateById(user);
        //查询user现在所拥有的roleId
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        List<UserRole> list = userRoleService.list(queryWrapper);
        if (list.size() > 0) {
            //保存了此user对应的所有roleId
            List<Integer> allRoleId = new LinkedList<>();
            for (UserRole userRole : list) {
                allRoleId.add(userRole.getRoleId());
            }
            //allroleid{A,B,C} roleIds{B,C,D}
            //allRoleId减去roleIds,剩下的roleId对应的userRole根据userId删除
            //需要删除的RoleIds
            List<Integer> delRoleIds = new LinkedList<>();
            for (Integer integer : allRoleId) {
                if (!roleIds.contains(integer)) {
                    delRoleIds.add(integer);
                }
            }
            if (delRoleIds != null && delRoleIds.size() > 0) {
                QueryWrapper<UserRole> delQuery = new QueryWrapper<>();
                delQuery.eq("user_id", user.getId());
                delQuery.in("role_id", delRoleIds);
                userRoleService.remove(delQuery);
            }
            //roleIds减去user所拥有的所有roleId,剩下的roleId需要根据userId添加
            //需要添加的RoleIds
            List<Integer> addRoleIds = new LinkedList<>();
            for (Integer integer : roleIds) {
                if (!allRoleId.contains(integer)) {
                    addRoleIds.add(integer);
                }
            }
            if (addRoleIds != null && addRoleIds.size() > 0) {
                List<UserRole> addUserRoles = new LinkedList<>();
                for (Integer addRoleId : addRoleIds) {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(user.getId());
                    userRole.setRoleId(addRoleId);
                    addUserRoles.add(userRole);
                }
                userRoleService.saveBatch(addUserRoles);
            }
        } else {
            for (Integer roleId : roleIds) {
                UserRole userRole = new UserRole();
                userRole.setUserId(user.getId());
                userRole.setRoleId(roleId);
                userRoleService.save(userRole);
            }
        }
        if (updateById) {
            return super.success(user);
        } else {
            return super.fail(user);
        }
    }

    @RequestMapping("/rePassword")
    public ReturnBean rePassword(String userId, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", userId);
        User one = userService.getOne(queryWrapper);
        one.setPassword(MD5Utils.md5(password, one.getSalt()));
        boolean updateById = userService.updateById(one);
        if (updateById) {
            return super.success(one);
        } else {
            return super.fail(one);
        }
    }
    /**
     * 更新用户基本信息
     *
     * @param user 实体类
     * @return ReturnBean
     * @createBy Enzo
     * @createTime 2020/12/23 17:44
     */
    @PutMapping("/updateUserInfo")
    public ReturnBean updateUserInfo(User user) {
        User newUser = userService.getById(user.getId());
        try {
            userService.updateById(user);

            return success(null);
        } catch (Exception e) {
            return fail(null);
        }

    }
}

